package sword_offer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Synhard
 * @version 1.0
 * @class Code42
 * @description 剑指 Offer 38. 字符串的排列
 * 输入一个字符串，打印出该字符串中字符的所有排列。
 *
 *
 * 你可以以任意顺序返回这个字符串数组，但里面不能有重复元素。
 *
 *
 * 示例:
 *
 * 输入：s = "abc"
 * 输出：["abc","acb","bac","bca","cab","cba"]
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-07-08 8:45
 */
public class Code42 {
    public static void main(String[] args) {

    }

    public String[] permutation(String s) {
        Set<String> res = new HashSet<>();
        char[] chars = new char[s.length()];
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            chars[i] = s.charAt(i);
        }
        dfs(chars, 0, res);
        String[] ans = new String[res.size()];

        for (String str : res) {
            ans[index++] = str;
        }
        return ans;
    }

    private void dfs(char[] chars, int cur, Set<String> res) {
        if (cur == chars.length - 1) {
            StringBuilder sb = new StringBuilder();
            for (char c : chars) {
                sb.append(c);
            }
            res.add(sb.toString());
            return;
        }
        for (int i = cur; i < chars.length; i++) {
            swap(chars, cur, i);
            dfs(chars, cur + 1, res);
            swap(chars, cur, i);
        }
    }

    public static void swap(char[] arr, int pos1, int pos2) {
        char temp = arr[pos1];
        arr[pos1] = arr[pos2];
        arr[pos2] = temp;
    }

}
